package com.example.adminvue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.adminvue.domain.LoginUser;
import com.example.adminvue.domain.Menu;
import com.example.adminvue.domain.SysRole;
import com.example.adminvue.domain.User;
import com.example.adminvue.mapper.MenuMapper;
import com.example.adminvue.mapper.SysRoleMapper;
import com.example.adminvue.mapper.UserMapper;
import com.example.adminvue.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 无需配置spring security，自动生效
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(queryWrapper);
        //如果没有查询到用户信息抛出异常
        if(Objects.isNull(user)) {
            throw new RuntimeException("用户名或者密码错误");
        }
        //查询用户角色列表
        List<SysRole> roleList = sysRoleMapper.selectRolePermissionByUserId(user.getUserId());
        List<Long> roleids = roleList.stream().map(SysRole::getRoleId).collect(Collectors.toList());
        Long[] roleidArray = new Long[roleids.size()];
        roleidArray=roleids.toArray(roleidArray);
        user.setRoles(roleList);
        user.setRoleId(roleList.get(0).getRoleId());
        user.setRoleIds(roleidArray);
        //查询对应的用户权限信息
        List<String> list;
        if(SecurityUtils.isAdmin(user.getUserId())){
            list = new ArrayList<>();
            list.add("*:*:*");
        }
        else{
            list = menuMapper.selectPermsByUserId(user.getUserId());
        }

        return new LoginUser(user,list,roleList);
    }
}
